/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Oksana_Moroz
 */
public class Pr2 {

    private static void merge(int[] a, final int p, final int q, final int r) {        
        int[] buff = new int[r - p + 1];
        int ip = p;
        int iq = q + 1;
        int ib = 0;
        while (ip <= q && iq <= r) {
            if (a[ip] < a[iq]) {
                buff[ib++] = a[ip++];
            } else {
                buff[ib++] = a[iq++];
            }
        }
        for (int i = ip; i <= q; i++) {
            buff[ib++] = a[i];
        }
        for (int i = iq; i <= r; i++) {
            buff[ib++] = a[i];
        }
        for (int i = p; i <= r; i++) {
            a[i] = buff[i - p];
        }
    }

    public static void mergeSort(final int[] a, final int p, final int r) {
        if (p < r) {
            final int q = (p + r) / 2;
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {                    
                    mergeSort(a, p, q);
                }
            });
            t.start();
            mergeSort(a, q + 1, r); 
            try {
                t.join();                             
                merge(a, p, q, r);
            } catch (InterruptedException ex) {
                Logger.getLogger(Pr2.class.getName()).log(Level.SEVERE, null, ex);
            }    
        }
    }
    
    public static void main(String[] args) {
        int[] a = {7, 2, 0, 1, 7, 3, 9, 4, 6, 7, 3, 2, 7};
        mergeSort(a, 0, a.length - 1);
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }
}